//
//  FilmTicketBookConfirmView.m
//  ELife
//
//  Created by  刘奇男 on 11-5-22.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "FilmTicketBookConfirmViewController.h"
#import "GDataXMLNode.h"
#import "GTMBase64.h"
#import "Cinema.h"
#import "AlertView.h"
#import "LoginController.h"
#import "GetMyData.h"

@implementation FilmTicketBookConfirmViewController

@synthesize phoneNumberLabel, costLabel, countLabel, banlanceLabel, ticketTypeLabel, cinema;

- (void)search
{
    NSString* userid = [GetMyData getUserId];
    if (userid == nil)
    {
        NSString* userid = [GetMyData getUserId];
        if (userid == nil)
        {
            
            LoginController* lc = [[LoginController alloc] init:self];
            [self.navigationController pushViewController:lc animated:YES];
            [lc release];
            return;
            
        }
        
    }
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"user.php"]];
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:2];
    [param setObject:@"getaccountinfo" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestDetailFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
}

- (void)iRequestDetailFinished:(NSData *)response
{
    [app hideProgressDialog];
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"-----rootElement-----%@\n", rootElement);
    
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"-----headsElement-----%@\n", headsElement);
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
        //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        [alert show];
         [alert setTag:11];
        [alert release];
        return;
    }
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    //    <msg><head><returncode>0</returncode><transcode>getaccountinfo</transcode></head><body><user_id>318813</user_id><score>135</score><account>0.0000</account><daijingquan>0.0000</daijingquan></body></msg>
    
    //某个具体节点的文本内容
    NSString* score = [[[bodyElement elementsForName:@"score"]objectAtIndex:0] stringValue];
    NSString* account = [[[bodyElement elementsForName:@"account"]objectAtIndex:0] stringValue];
    NSString* daijingquan = [[[bodyElement elementsForName:@"daijingquan"]objectAtIndex:0] stringValue];
    
    banlanceLabel.text = account;
    
    [doc release];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
    
    [costLabel release];
    [countLabel release];
    [ticketTypeLabel release];
    [phoneNumberLabel release];
    [banlanceLabel release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

-(void) goLogin
{
    LoginController *controller = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
    
    [self.navigationController pushViewController:controller animated:YES];
    [controller release];
}

- (void)requestPay
{
    NSString* userid = [GetMyData getUserId];
    if (userid == nil)
    {
        LoginController* lc = [[LoginController alloc] init:self];
        lc.view.tag = 2001;
        //        [self.view addSubview:lc.view];
        [self.navigationController pushViewController:lc animated:NO];
        [lc release];
        return;
        
    }
    [app showProgressDialog:@"请稍候"];
    
    /**
     10.3 余额购买电影票
     请求地址: /cinema.php
     请求参数:   
     action    => 'cinema_charge';
     user_id   => 用户ID;
     phone     => 手机号码 
     kind_id   => 兑换券类型;
     num	  => 购买数量(最多6张);
     
     返回参数: 
     cinema_id  => 电影院ID;
     date       => 日期;
     
     返回格式事例: 
     <?xml version="1.0" encoding="UTF-8"?><msg><head><returncode>0</returncode><transcode>cinema_charge</transcode></head><body><cinema_id>77</cinema_id><date>20110215</date></body></msg>
     */
    
    NSString* host =  [[NSBundle mainBundle] localizedStringForKey:(@"BussinessHost") value:@"" table:nil];
    NSURL* url = [[NSURL alloc] initWithString:[host stringByAppendingString:@"cinema.php?"]];
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]initWithCapacity:5];
    [param setObject:@"cinema_charge" forKey:@"action"];
    [param setObject:[[NSBundle mainBundle] localizedStringForKey:(@"ClientVersion") value:@"" table:nil] forKey:@"version"];
    [param setObject:[GetMyData getUserId] forKey:@"user_id"];//111111
    [param setObject:cinema.userPhone forKey:@"phone"];
    [param setObject:[NSString stringWithFormat:@"%i", cinema.cardKindId] forKey:@"kind_id"];
    [param setObject:[NSString stringWithFormat:@"%i", cinema.count] forKey:@"num"];
    
    NSLog(@"--Param-----------%@\n", param);
    
    NSDictionary* dic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:url, @"iRequestFinished:", nil] forKeys:[NSArray arrayWithObjects:@"url", @"requestMethod", nil]];
    
    [[app httpRequestPoint]openUrl:dic postParam:param target:self];
    
    [param release];
}

#pragma mark -
#pragma mark 联网回调
- (void)iRequestFinished:(NSData *)response
{    

    [app hideProgressDialog];
//    NSLog(@"-----cinemasElement-----%@\n", [GTMBase64 decodeData:response]);
    
    
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[GTMBase64 decodeData:response] options:0 error:nil];
    
    
    GDataXMLElement* rootElement = [doc rootElement];    
    NSLog(@"-----rootElement-----%@\n", rootElement);
    
    [doc release];
    
    GDataXMLElement* headsElement = [[rootElement elementsForName:@"head"]objectAtIndex:0];
    NSLog(@"-----headsElement-----%@\n", headsElement);
    
    GDataXMLNode* returnCode = [[headsElement elementsForName:@"returncode"] objectAtIndex:0];
    NSInteger code = [[returnCode stringValue] intValue];
    if (code == -105){
//        [AlertView showAlert:@"请先登录" action:@"goLogin"];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登录"
                                                       delegate:self cancelButtonTitle:@"取消" otherButtonTitles: @"确定", nil];
        
        [alert setTag:11];
        [alert show];	
        [alert release];
        return;
    } else if (code != 0) {
        [AlertView showAlert:@"购买失败"];
        return;
    }
    
    GDataXMLElement* bodyElement = [[rootElement elementsForName:@"body"]objectAtIndex:0];
    
    
//    NSLog(@"-----cinemasElement-----%@\n", cinemasElement);
    
    //        [AlertView showAlert:@"请先登录" action:@"goLogin"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"购买成功"
                                                   delegate:self cancelButtonTitle:nil otherButtonTitles: @"确定", nil];
    [alert setTag:12];
    [alert show];
    [alert release];
}

#pragma mark -
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView tag] == 11)
    {
        if (buttonIndex == 1){
            LoginController *controller = [[LoginController alloc] initWithNibName:@"LoginController" bundle:nil];
        
            [self.navigationController pushViewController:controller animated:YES];
            [controller release];
        }
        return; 
       
    } else if ([alertView tag] == 12)
    {
        [self.navigationController popViewControllerAnimated:YES];
        
        return;
    }
	// use "buttonIndex" to decide your action
	//
//    NSLog(@"======ButtonIndex : %i\n", buttonIndex);
//    if (buttonIndex == 1){
//        [self goLogin];
//    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    app = [ELifeAppDelegate App];
    [super viewDidLoad];
    
    [costLabel setText:[NSString stringWithFormat:@"%i", self.cinema.cardKindValue]];
    [countLabel setText:[NSString stringWithFormat:@"%i", self.cinema.count]];
    [ticketTypeLabel setText:self.cinema.cardKindName];
    [phoneNumberLabel setText:self.cinema.userPhone];
}

-(IBAction) banlanceBuy:(id)sender
{
    [self requestPay];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    
    [self search];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
